import re
from rest_framework import serializers
from Login.models import user, Code
import datetime
from Login.utils import encrpty
from Login.service.login import makeCodeBeInvalid


# 注册序列化校验
class RegisterSerializer(serializers.ModelSerializer):
    verify_password = serializers.CharField(max_length=64)
    code = serializers.CharField(max_length=32)

    class Meta:
        model = user
        fields = ['username', 'password', 'verify_password', 'phone', 'email', 'code']
        read_only_fields = ('verify_password', 'code')

    def validate_password(self, data):
        # print(data)
        if not data:
            raise serializers.ValidationError('请输入密码')
        return encrpty.md5(data)

    def validate_verify_password(self, data):
        if not data:
            raise serializers.ValidationError("请确定密码")
        return encrpty.md5(data)

    def validate_code(self, data):
        # print("-*" * 50)
        # print(self.initial_data)
        email = self.initial_data.get("email")
        if not data:
            raise serializers.ValidationError("未输入验证码")
        # 判断验证码是否过期
        code_verify = Code.objects.order_by('-create_time').first()  # 按倒序取出返回的第一个验证码
        # print(code_verify,"---------------")

        if code_verify:
            # 判断验证码状态
            if code_verify.status == 0:
                raise serializers.ValidationError("验证码已失效")
            create_time = code_verify.create_time
            nowTime = datetime.datetime.now()
            if nowTime > create_time + datetime.timedelta(minutes=5):
                raise serializers.ValidationError("该验证码已经过期")
            if data != code_verify.code:
                raise serializers.ValidationError("验证码不正确，请重新输入")
            makeCodeBeInvalid(email=email)
        return data

    def validate_phone(self, data):
        if not data:
            raise serializers.ValidationError("请输入手机号")
        pattern = re.compile(r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$')
        if not re.match(pattern, data):
            raise serializers.ValidationError("该手机号码格式错误，请确定格式正确后重新输入")
        if user.objects.filter(phone=data).exists():
            raise serializers.ValidationError("该手机号已被注册")
        return data

    def validate_email(self, data):
        if not data:
            raise serializers.ValidationError('请输入邮箱账号')
        pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
        if not re.match(pattern, data):
            raise serializers.ValidationError("该邮箱格式错误，请确定格式正常后重新输入")
        if user.objects.filter(email=data).exists():
            raise serializers.ValidationError('该邮箱已被注册')
        return data


# 重置密码序列化校验（登录后）
class alter_passwordSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=32)
    password_confirm = serializers.CharField(max_length=64)

    class Meta:
        model = user
        fields = ['code', 'password', 'password_confirm']
        read_only_fields = ('code', 'password_confirm')

    def validate_code(self, data):
        email = self.initial_data.get("email")
        if not data:
            raise serializers.ValidationError("未输入验证码")
        # 判断验证码是否过期
        code_verify = Code.objects.order_by('-create_time').first()  # 按倒序取出返回的第一个验证码
        if code_verify:
            # 判断验证码状态
            if code_verify.status == 0:
                raise serializers.ValidationError("验证码已失效")
            create_time = code_verify.create_time
            nowTime = datetime.datetime.now()
            if nowTime > create_time + datetime.timedelta(minutes=5):
                raise serializers.ValidationError("该验证码已经过期")
            if data != code_verify.code:
                raise serializers.ValidationError("验证码不正确，请重新输入")
            makeCodeBeInvalid(email=email)
        return data

    def validate_password(self, data):
        if not data:
            raise serializers.ValidationError("请输入密码")
        return encrpty.md5(data)

    def validate_password_confirm(self, data):
        if not data:
            raise serializers.ValidationError("请确定密码")
        password = self.initial_data.get("password")
        if password != data:
            raise serializers.ValidationError("两次密码输入不一致，请重新输入")
        return encrpty.md5(data)


# 修改个人信息序列化校验
class alterInformationSerializer(serializers.ModelSerializer):
    substrings = ['tmd', 'fuck', '傻逼']  # 存放敏感词
    # 覆盖原字段，使其可以单独填写
    username = serializers.CharField(required=False, max_length=50)
    gender = serializers.CharField(required=False, max_length=6)
    # phone = serializers.CharField(required=False, max_length=15)
    code = serializers.CharField(required=False, max_length=32)

    class Meta:
        model = user
        fields = ['username', 'birthday', 'gender', 'province', 'city', 'country', 'introduce', 'code', 'email']

    def validate_email(self, value):
        pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
        if not re.match(pattern, value):
            raise serializers.ValidationError("该邮箱格式错误，请确定格式正常后重新输入")
        if user.objects.filter(email=value).exists():
            raise serializers.ValidationError('该邮箱已被注册')
        return value
    #
    # def validate_phone(self, value):
    #     pattern = re.compile(r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$')
    #     if not re.match(pattern, value):
    #         raise serializers.ValidationError("该手机号码格式错误，请确定格式正确后重新输入")
    #     if user.objects.filter(phone=value).exists():
    #         raise serializers.ValidationError("该手机号已被注册")
    #     return value

    def validate_introduce(self, value):
        if len(value) > 50:
            raise serializers.ValidationError("输入不能大于50字")
        for substring in self.substrings:
            if substring in value:
                raise serializers.ValidationError(f"请对简介进行修改，不要使用敏感词:{substring}！！！")
        return value

    def validate_code(self, value):
        email = self.initial_data.get("email")
        if not value:
            raise serializers.ValidationError("未输入验证码")
        # 判断验证码是否过期
        code_verify = Code.objects.order_by('-create_time').first()  # 按倒序取出返回的第一个验证码
        if code_verify:
            # 判断验证码状态
            if code_verify.status == 0:
                raise serializers.ValidationError("验证码已失效")
            create_time = code_verify.create_time
            nowTime = datetime.datetime.now()
            if nowTime > create_time + datetime.timedelta(minutes=5):
                raise serializers.ValidationError("该验证码已经过期")
            if value != code_verify.code:
                raise serializers.ValidationError("验证码不正确，请重新输入")
            makeCodeBeInvalid(email=email)
        return value


class UserSerializer(serializers.ModelSerializer):
    password_confirm = serializers.CharField(max_length=64)
    code = serializers.CharField(max_length=32)

    class Meta:
        model = user
        fields = ['email', 'password', 'password_confirm', 'code']

    def validate_email(self, value):
        pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
        if not re.match(pattern, value):
            raise serializers.ValidationError("该邮箱格式错误，请确定格式正常后重新输入")
        return value

    def validate_code(self, data):
        email = self.initial_data.get("email")
        if not data:
            raise serializers.ValidationError("未输入验证码")
        # 判断验证码是否过期
        code_verify = Code.objects.order_by('-create_time').first()  # 按倒序取出返回的第一个验证码
        if code_verify:
            # 判断验证码状态
            if code_verify.status == 0:
                raise serializers.ValidationError("验证码已失效")
            create_time = code_verify.create_time
            nowTime = datetime.datetime.now()
            if nowTime > create_time + datetime.timedelta(minutes=5):
                raise serializers.ValidationError("该验证码已经过期")
            if data != code_verify.code:
                raise serializers.ValidationError("验证码不正确，请重新输入")
            makeCodeBeInvalid(email=email)
        return data

    def validate_password(self, data):
        if not data:
            raise serializers.ValidationError("请输入密码")
        return encrpty.md5(data)

    def validate_password_confirm(self, data):
        if not data:
            raise serializers.ValidationError("请确定密码")
        password = self.initial_data.get("password")
        if password != data:
            raise serializers.ValidationError("两次密码输入不一致，请重新输入")
        return encrpty.md5(data)


# 更改头像
class changeAvatarSerializer(serializers.ModelSerializer):

    class Meta:
        model = user
        fields = ['avatar']

    # def validate_avatar(self, value):
    #     print("-" * 50)
    #     image = Image.open(value)
    #     image_format = image.format
    #     size = value.size
    #     if image_format != 'JPEG':
    #         raise serializers.ValidationError("不支持该类型文件，请重新上传")
    #     if size > 500*1024:
    #         raise serializers.ValidationError("文件过大，请重新选择")
    #     return value

        # data_url = data.get('avatar')
        # _, base64_str = data_url.split('base64,')
        #
        # # 解码图像数据
        # image_data = base64.b64decode(base64_str)
        #
        # # 使用 PIL 打开图像数据
        # image = Image.open(io.BytesIO(image_data))
        #
        # # 获取图片类型
        # image_format = image.format  # 可能是 JPEG, PNG, BMP 等
        # if image_format != 'JPEG':
        #     raise serializers.ValidationError("不支持该类型文件，请重新上传")
        # # 获取图片大小,并将字节大小转换为 KB
        # image_size_kb = len(image_data) / 1024
        # if image_size_kb > 500:
        #     raise serializers.ValidationError("文件过大，请重新选择")
        # return image_data


    # 自定义文件类型验证函数
    # def validate_file_extension(self, data):
    #     # 获取文件的后缀名
    #     file_name, file_extension = os.path.splitext(data)
    #     return file_extension
    #
    # def is_text_file(self, data):
    #     # 判断是否符合文件类型
    #     text_extensions = ['.jpg']
    #     file_extension = self.validate_file_extension(data)
    #     if file_extension in text_extensions:
    #         return data
    #     else:
    #         serializers.ValidationError("不支持该类型文件，请重新上传")
    #
    # def validate_file_size(self, data):
    #     # 自定义文件大小验证函数
    #     file_size = os.path.getsize(data)
    #     if file_size > 512000:
    #         serializers.ValidationError("文件过大，请重新选择")
    #     else:
    #         return data


